#include "stdafx.h"
#include "GpuBufferManager.h"

#include "Log.h"

namespace Cvekas {

GpuBufferManager::GpuBufferManager(D3DDevicePtr device)
	:
device(device)
{
	LOG("GpuBufferManager created");
}

GpuBufferManager::~GpuBufferManager()
{
	LOG("Destroying GpuBufferManager");
}

IndexBufferPtr GpuBufferManager::createIndexBuffer(const std::string &name, bool sixteen_bits, uint index_count, bool dynamic)
{
	ResourceId id = getUniqueId(name);
	GpuBufferPtr index_buffer(new IndexBuffer(id, device, name, sixteen_bits, index_count, dynamic));
	return boost::static_pointer_cast<IndexBuffer>(insert(name, index_buffer, id));
}

VertexBufferPtr GpuBufferManager::createVertexBuffer(const std::string &name, Cvekas::VertexFormat format, uint vertex_count, bool dynamic)
{
	ResourceId id = getUniqueId(name);
	GpuBufferPtr vertex_buffer(new VertexBuffer(id, device, name, format, vertex_count, dynamic));
	return boost::static_pointer_cast<VertexBuffer>(insert(name, vertex_buffer, id));
}

IndexBufferPtr GpuBufferManager::getIndexBuffer(const std::string &name)
{
	GpuBufferPtr index_buffer = get(name);
	return boost::dynamic_pointer_cast<IndexBuffer>(index_buffer);
}

IndexBufferPtr GpuBufferManager::getIndexBuffer(Cvekas::ResourceId id)
{
	GpuBufferPtr index_buffer = get(id);
	return boost::dynamic_pointer_cast<IndexBuffer>(index_buffer);
}

VertexBufferPtr GpuBufferManager::getVertexBuffer(const std::string &name)
{
	GpuBufferPtr vertex_buffer = get(name);
	return boost::dynamic_pointer_cast<VertexBuffer>(vertex_buffer);
}

VertexBufferPtr GpuBufferManager::getVertexBuffer(Cvekas::ResourceId id)
{
	GpuBufferPtr vertex_buffer = get(id);
	return boost::dynamic_pointer_cast<VertexBuffer>(vertex_buffer);
}

void GpuBufferManager::onDeviceLost()
{
	// If resources is empty, resources.begin() throw exception 
	if(resources.empty())
		return;

	for(resources_itr = resources.begin(); resources_itr != resources.end(); ++resources_itr)
	{
		GpuBufferPtr buffer = *resources_itr;
		if(bool(buffer))
			buffer->onDeviceLost();
	}
}

void GpuBufferManager::onDeviceReset()
{
	// If resources is empty, resources.begin() throw exception 
	if(resources.empty())
		return;

	for(resources_itr = resources.begin(); resources_itr != resources.end(); ++resources_itr)
	{
		GpuBufferPtr buffer = *resources_itr;
		if(bool(buffer))
			buffer->onDeviceReset();
	}
}

} // namespace

